using Microsoft.EntityFrameworkCore;
using STD.Services.UserService.Domain.Entities;
using STD.Shared.Infrastructure.Database;

namespace STD.Services.UserService.Infrastructure.Data;

/// <summary>
/// 用户数据库上下文
/// </summary>
public class UserDbContext : DbContext
{
    private readonly IDatabaseProvider _databaseProvider;
    
    public UserDbContext(DbContextOptions<UserDbContext> options, IDatabaseProvider databaseProvider) 
        : base(options)
    {
        _databaseProvider = databaseProvider;
    }
    
    /// <summary>
    /// 用户表
    /// </summary>
    public DbSet<User> Users { get; set; }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        
        // 配置用户实体
        modelBuilder.Entity<User>(entity =>
        {
            entity.ToTable("Users");
            
            entity.HasKey(e => e.Id);
            
            entity.Property(e => e.Username)
                .IsRequired()
                .HasMaxLength(100);
            
            entity.Property(e => e.Email)
                .IsRequired()
                .HasMaxLength(255);
            
            entity.Property(e => e.PasswordHash)
                .IsRequired()
                .HasMaxLength(255);
            
            entity.Property(e => e.FullName)
                .IsRequired()
                .HasMaxLength(200);
            
            entity.Property(e => e.PhoneNumber)
                .HasMaxLength(20);
            
            // 创建唯一索引
            entity.HasIndex(e => e.Username)
                .IsUnique();
            
            entity.HasIndex(e => e.Email)
                .IsUnique();
            
            // 软删除过滤器
            entity.HasQueryFilter(e => !e.IsDeleted);
        });
    }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            // 这里应该从配置中获取连接字符串
            // 在实际应用中，连接字符串应该在Program.cs中配置
        }
    }
} 